package com.gk.study.controller;

import com.gk.study.common.APIResponse;
import com.gk.study.common.ResponeCode;
import com.gk.study.entity.User;
import com.gk.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;
    
    @Value("${File.uploadPath}")
    private String uploadPath;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public APIResponse login(@RequestBody Map<String, String> loginData) {
        try {
            String username = loginData.get("username");
            String password = loginData.get("password");
            
            if (username == null || password == null) {
                return new APIResponse<>(ResponeCode.FAIL, "用户名和密码不能为空");
            }

            // 检查用户是否存在
            User user = service.getUserByUserName(username);
            if (user == null) {
                return new APIResponse<>(ResponeCode.FAIL, "用户不存在");
            }

            // 检查密码
            if (!password.equals(user.getPassword())) {
                return new APIResponse<>(ResponeCode.FAIL, "密码错误");
            }

            // 检查用户状态
            if (user.getStatus() != 1) {
                return new APIResponse<>(ResponeCode.FAIL, "用户已被禁用");
            }

            // 生成token
            String token = UUID.randomUUID().toString().replace("-", "");
            user.setToken(token);
            user.setLastLoginTime(LocalDateTime.now());
            service.updateUser(user);

            // 登录成功，返回用户信息（不包含密码）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("nickname", user.getNickname());
            userInfo.put("role", user.getRole());
            userInfo.put("avatar", user.getAvatar());
            userInfo.put("token", token);

            return new APIResponse<>(ResponeCode.SUCCESS, userInfo);
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.INTERNAL_SERVER_ERROR, "登录失败: " + e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public APIResponse register(@RequestBody Map<String, String> registerData) {
        try {
            String username = registerData.get("username");
            String password = registerData.get("password");
            String nickname = registerData.get("nickname");
            
            if (username == null || password == null) {
                return new APIResponse<>(ResponeCode.FAIL, "用户名和密码不能为空");
            }

            // 检查用户是否已存在
            User existingUser = service.getUserByUserName(username);
            if (existingUser != null) {
                return new APIResponse<>(ResponeCode.FAIL, "用户名已存在");
            }

            // 创建新用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            newUser.setNickname(nickname != null ? nickname : username);
            newUser.setRole("user");
            newUser.setStatus(1);
            newUser.setCreateTime(LocalDateTime.now());

            service.createUser(newUser);

            return new APIResponse<>(ResponeCode.SUCCESS, "注册成功");
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.INTERNAL_SERVER_ERROR, "注册失败: " + e.getMessage());
        }
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public APIResponse list(@RequestParam(required = false) String keyword) {
        List<User> list = service.getUserList(keyword);
        return new APIResponse(ResponeCode.SUCCESS, "查询成功", list);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public APIResponse create(User user) {
        service.createUser(user);
        return new APIResponse(ResponeCode.SUCCESS, "创建成功");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public APIResponse update(User user) {
        service.updateUser(user);
        return new APIResponse(ResponeCode.SUCCESS, "更新成功");
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public APIResponse delete(@RequestParam String ids) {
        service.deleteUser(ids);
        return new APIResponse(ResponeCode.SUCCESS, "删除成功");
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public APIResponse detail(@RequestParam String userId) {
        User user = service.getUserDetail(userId);
        return new APIResponse(ResponeCode.SUCCESS, "查询成功", user);
    }

    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    public APIResponse updateUserInfo(User user) {
        // 处理头像文件上传
        if (user.getAvatarFile() != null && !user.getAvatarFile().isEmpty()) {
            try {
                String fileName = saveAvatar(user.getAvatarFile());
                user.setAvatar(fileName);
            } catch (Exception e) {
                return new APIResponse(ResponeCode.FAIL, "头像上传失败: " + e.getMessage());
            }
        }
        
        service.updateUser(user);
        return new APIResponse(ResponeCode.SUCCESS, "更新成功");
    }
    
    private String saveAvatar(MultipartFile file) throws Exception {
        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;
        
        // 保存文件到正确的路径
        String avatarPath = uploadPath + "/avatar/";
        java.io.File uploadDir = new java.io.File(avatarPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        
        java.io.File destFile = new java.io.File(avatarPath + fileName);
        file.transferTo(destFile);
        
        return fileName;
    }

    @RequestMapping(value = "/updateUserPwd", method = RequestMethod.POST)
    public APIResponse updateUserPwd(@RequestBody User user) {
        service.updateUser(user);
        return new APIResponse(ResponeCode.SUCCESS, "密码更新成功");
    }
} 